package com.apptonelabs.pnrenquiry;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class PnrEnquiryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// Get the PNR
		String pnr = req.getParameter("pnr");
		String of = req.getParameter("of");
		String mobile = req.getParameter("m");
		if(of == null) {
			of = "json";
		} if(of.equalsIgnoreCase("xml") || of.equalsIgnoreCase("json")) {
			// check only
		} else {
			of = "json";
		}
		
		String ope = "FAILED";
		
		resp.setContentType("text/html");
		
		if(pnr == null) {
			resp.getWriter().println("440,Empty PNR");
			resp.setStatus(440);
		} else if(pnr.length() == 10 ) {
			// PNR should be a 10 digit number
			try {
				Long.parseLong(pnr);
				
				String url = "http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_10521.cgi";
				// Extract the PNR URL
				/* try {
					PNRStatusCrawller check = new PNRStatusCrawller();
					StringBuffer data = check.getPNRHtml("http://www.indianrail.gov.in/pnr_Enq.html");
					if(data != null) {
						url = check.parseHtml1(data);
						if(url == null) {
							resp.setStatus(446);
							resp.getWriter().println("446,Error Processing PNR. Not able to get the URL from Peer website");
							return;
						}
					}
				} catch (Exception e) {
					resp.setStatus(447);
					resp.getWriter().println("447,Error Processing PNR. Not able to get the URL from Peer website");
					return;
				}
				*/
				
				try {
					String reqStr = "lccp_pnrno1=" + pnr + "&lccp_cap_val=13667&lccp_capinp_val=13667&submitpnr=Get+Status";
					PNRStatusCrawller check = new PNRStatusCrawller();
					StringBuffer data = check.getPNRResponse(reqStr, url);
					if(data != null) {
						PNRStatus pnrStatus = check.parseHtml2(data);
						if(pnrStatus != null && (pnrStatus.getTrainDetails() != null && pnrStatus.getTrainDetails().getName() != null)) {
							pnrStatus.setPnr(pnr);
							
							// Convert to XML
							PNRResponse res = new PNRResponse();
							res.setStatus(pnrStatus);
							
							if(of.equalsIgnoreCase("xml")) {
								JAXBContext jaxbContext = JAXBContext.newInstance(PNRResponse.class);
								Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
								// output pretty printed
								jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
								
								ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
								jaxbMarshaller.marshal(res, bout);
								
								ope = "SUCCESS";
								resp.setStatus(200);
								resp.setContentType("text/xml");
								resp.getWriter().println(new String(bout.toByteArray()));
							} else if(of.equalsIgnoreCase("json")) {
								Gson gson = new Gson();
								
								String json = gson.toJson(res);
								
								ope = "SUCCESS";
								resp.setStatus(200);
								resp.setContentType("text/json");
								resp.getWriter().println(json);
							}
						} else {
							resp.setStatus(443);
							resp.getWriter().println("443,Error Processing PNR. Not able to get the Response from Peer website");
							return;
						}
					}
				} catch(Exception e) {
					resp.setStatus(442);
					resp.getWriter().println("442,Error Processing PNR " + e.getMessage());
				}
				
			} catch (Exception e) {
				resp.setStatus(441);
				resp.getWriter().println("441,Invalid PNR");
			}
		} else {
			resp.setStatus(444);
			resp.getWriter().println("444,Invalid PNR");
		}
		
		try {
			// Log the data
			if(mobile != null) {
				try {
			        Key PNRKey = KeyFactory.createKey("PNR", pnr);
			        Date date = new Date();
			        Entity pnrQuery = new Entity("PNRQuery", PNRKey);
			        pnrQuery.setProperty("date", date);
			        pnrQuery.setProperty("pnr", pnr);
			        pnrQuery.setProperty("mobile", mobile);
			        pnrQuery.setProperty("rcode", ope);
		
			        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			        datastore.put(pnrQuery);
				} catch (Exception e) {
					//ignore
				}
			}
		} catch (Exception e) {
			//ignore
		}
	}

}
